<?php


namespace app\api\console;


use app\api\service\OrderService;
use app\api\service\PharmacyOrderService;
use app\api\service\PharmacyService;
use app\api\service\WechatInfoService;
use app\common\wechat\TemplateMessage;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;

class DealDistributeOrderCommand extends Command
{

    // ...
    protected function configure()
    {
        $this
            // 命令的名字（"think" 后面的部分）
            ->setName('app:distribute-order')

            // 运行 "php think list" 时的简短描述
            ->setDescription('派发药品订单给仓储点.')

            // 运行命令时使用 "--help" 选项时的完整命令描述
            ->setHelp("派发药品订单给仓储点...")
        ;
    }

    protected function execute(Input $input, Output $output)
    {
        $appId = \config('wechat.appid');
        $orderService = new OrderService();

        $pharmacyOrderService = new PharmacyOrderService();

        //获取待派订单
        $orders = $orderService->fetchHasPayOrder();

        $geoOption = ['count'=>2, 'ASC', 'WITHCOORD', 'WITHDIST'];

        $wechatInfoService = new WechatInfoService();

        $redis = new \Redis();

        $rb = $redis->connect('127.0.0.1', 6379);

        if($rb){

            //redis连接成功

            $templatePushMessage = new TemplateMessage();

            $pharmacyService = new PharmacyService();

            foreach ($orders as $order){

                try{

                    $orderLatitude = $order['latitude'];

                    $orderLongitude = $order['longitude'];

                    $orderId = $order['id'];

                    //获取30公里范围内的最近的点
                    $data = $redis->geoRadius(PHARMACY_LOCATION, $orderLongitude, $orderLatitude, 30, 'km', $geoOption);

                    if($data){

                        //查询到最近的两个药店 返回的redis里面包含了药店的id
                        $pharmacyId = $data[0][0];

                        $isNeedRemind = false;

                        Db::startTrans();
                        $result = $pharmacyOrderService->addPharmacyOrder($pharmacyId, $orderId);
                        if($result !== false){

                            //更新订单的状态为已接单 待拣货
                            $re1 = $orderService->updateOrderStatus($orderId, 3);

                            if(!$re1){
                                Db::rollback();
                            }else{
                                $isNeedRemind = true;
                                Db::commit();
                            }
                        }else{
                            Db::rollback();
                        }

                        if($isNeedRemind){

                            $info = $pharmacyService->getPharmacyInfo($pharmacyId);

                            $pharmacyMobile = $info['pharmacy_mobile_phone'];

                            $openid = $pharmacyService->getOpenidByMobile($pharmacyMobile);
                            //收货人姓名
                            $receiveName = $order['recipients'];
                            //收货人电话
                            $receiveMobile = $order['recipientsMobile'];
                            //商品
                            $productName = '请点击详情里面查看';
                            //数量
                            $productCount = '请点击详情里面查看';
                            //订单号
                            $orderNo = sprintf("%08d", $order['id']);;
                            //添加订单号
                            $remark = "该订单的取货号是{$orderNo}";
                            $templateData['touser'] = $openid;
                            $templateData['template_id'] = 'rebYvkDafmrIZ8WxUjvPKyJzF-VczSaBzr3cZsao7yw';
                            $templateData['url'] = 'http://weixin.qq.com/download';
                            $templateData['data'] = ['first'=>['value'=>'您有新的待处理的订单，请点击详情处理！'],
                                "keyword1"=>['value'=>$order['addtime']],
                                "keyword2"=>['value'=>$receiveName],
                                "keyword3"=>['value'=>$receiveMobile],
                                "keyword4"=>['value'=>$productName],
                                "keyword5"=>['value'=>$productCount],
                                "remark"=>['value'=>$remark]
                            ];
                            $accessToken = $wechatInfoService->getAccessToken($appId);

                            $res = $templatePushMessage->pushTemplateMessage($templateData, $accessToken);

                        }

                    }

                }catch (\Exception $e){
                    var_dump($e);
                }
            }

            $redis->close();

        }
    }
}